package com.kfm.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@WebListener
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        String id = se.getSession().getId();
        System.out.println("session 被创建了: " + id);

        Object online = se.getSession().getServletContext().getAttribute("online");

        if (online instanceof AtomicInteger count){
            count.incrementAndGet();
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        String id = se.getSession().getId();
        System.out.println("session 被销毁了: " + id);
        Object online = se.getSession().getServletContext().getAttribute("online");

        if (online instanceof AtomicInteger count){
            count.decrementAndGet();
        }
    }
}
